import Cookies from 'js-cookie'
import utf8 from 'crypto-js/enc-utf8';
import aes from 'crypto-js/aes';
import ecb from 'crypto-js/mode-ecb';
import pkcs7 from 'crypto-js/pad-pkcs7';

export function handleNoStringToNull (obj = {}) {
  Object.keys(obj).forEach(key => {
    obj[key] === ''? null : obj[key]
  })
  return obj
}

export function getUrlPrefix() {
  let url = window.location.href
  let urlArr = url.split('/')
  let prefix = urlArr.filter(str => !!str.match(/hesuan/i))[0] || ''
  return prefix
}

// 横向滚动动画
export function scrollAnimation($el, distance) {
  setTimeout(() => {
    const dist = Math.ceil(distance/5)
    $el.scrollTo($el.scrollLeft+=dist, 0)
    distance -= dist
    if (Math.abs(dist)>5) {
      scrollAnimation($el, distance)
    } else {
      $el.scrollTo($el.scrollLeft+=dist, 0)
    }
  }, 2)

}

export function getCokie (name) {
  return Cookies.get(name)
}


/**
 * Aes-128-ecb加密
 */
export const encryptAes128 = (key = "BABA1Wk@@Lz7%?8v", value) => {
  if (key?.length !== 16) {
    key = "BABA1Wk@@Lz7%?8v"
  }
  let sKey = utf8.parse(key);
  let sValue = utf8.parse(value);
  let result = aes.encrypt(sValue, sKey, { mode: ecb, padding: pkcs7 });
  return result.toString()
}


/**
 * Aes-128-ecb解密
 */
export const decryptionAes128 = (key = "BABA1Wk@@Lz7%?8v", value) => {
  if (!value) return JSON.stringify("")

  try {
    if (key?.length !== 16) {
      key = "BABA1Wk@@Lz7%?8v"
    }
    let sKey = utf8.parse(key);
    let result = aes.decrypt(value, sKey, { mode: ecb, padding: pkcs7 })
    return utf8.stringify(result).toString();
  } catch {
    return JSON.stringify("")
  }

}
